#include "server.h"

Server::Server(QObject *parent) : QObject(parent)
{
    m_tcpServer = new QTcpServer();
    m_tcpServer->setMaxPendingConnections(10);

    connect(m_tcpServer,SIGNAL(newConnection()),this,SLOT(newConnectSlot()));
}

Server::~Server()
{
}

void Server::init(QString ip, int port)
{
    if(ip=="")
        m_tcpServer->listen(QHostAddress::AnyIPv4,port);
    else
        m_tcpServer->listen(QHostAddress(ip),port);
}

void Server::sendData(QString ip, QString data)
{
    m_mapClient.value(ip)->write(data.toLatin1());
}

void Server::sendData(QString ip, uchar *rawData)
{
    m_mapClient.value(ip)->write(QByteArray((char *)rawData));
}
void Server::sendData(QString ip, char *data,int len)
{
    m_mapClient.value(ip)->write(data,len);
}

void Server::newConnectSlot()
{
    QTcpSocket *tcp  =  m_tcpServer->nextPendingConnection();
    emit signal_socket_change(tcp->peerAddress().toString(),1);
    connect(tcp,SIGNAL(readyRead()),this,SLOT(readMessage()));
    m_mapClient.insert(tcp->peerAddress().toString(),tcp);

    connect(tcp,SIGNAL(disconnected()),this,SLOT(removeUserFromList()));
}

void Server::readMessage()
{
    QTcpSocket *socket = static_cast<QTcpSocket*> (sender());
   // qDebug() <<"ip =" << ip;
   // qDebug()<< socket->peerAddress().toString() << socket->readAll().toHex();
    //qDebug() <<"server  len = " << socket->readAll().toHex().length();
    emit signal_recv_data(socket->peerAddress().toString(),socket->readAll());

}

void Server::removeUserFromList()
{
    QTcpSocket *socket = static_cast<QTcpSocket*>(sender());
    emit signal_socket_change(socket->peerAddress().toString(),0);
    QMap<QString ,QTcpSocket *>::iterator it;
    for(it=m_mapClient.begin();it!=m_mapClient.end();it++)
    {
        if(it.key()== socket->peerAddress().toString())
        {
            m_mapClient.erase(it);
            break;
        }
    }
}

void Server::closeServer()
{
    m_tcpServer->close();
}
